package com.zh.note.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
public class FileUploadController {

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");


    @PostMapping("/upload")
    public String upload(MultipartFile uploadFile, HttpServletRequest request) {
        String realPath = request.getSession().getServletContext().getRealPath("/uploadFile/");
        String format = simpleDateFormat.format(new Date());
        // 本地生成路径
        File folder = new File(realPath + format);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        // 获取旧文件名
        String oldName = uploadFile.getOriginalFilename();
        // 生成新文件名
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            // 本地要上传的文件
            File dest = new File(folder, newName);
            uploadFile.transferTo(dest);
            String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/uploadFile/" + format + newName;
            return filePath;

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    @PostMapping("/upload")
    public String upload(@RequestPart("headImg") MultipartFile headImg,
                         @RequestPart("photo") MultipartFile[] photos,
                         HttpServletRequest request) throws IOException {

        if (!headImg.isEmpty()) {
            // 保存文件到服务
            String originalFilename = headImg.getOriginalFilename();
            headImg.transferTo(new File("D:\\" + originalFilename));
        }
        if (photos.length > 0) {
            for (MultipartFile photo : photos) {
                if (!photo.isEmpty()) {
                    String originalFilename = photo.getOriginalFilename();
                    photo.transferTo(new File("D:\\"+ originalFilename));
                }
            }
        }


        return null;
    }
}
